package cn.java75.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author oldliu
 * @since 1.0
 */
public class MyBatisUtil {
    private MyBatisUtil() {
    }

    private static SqlSessionFactory factory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("初始化失败！");
        }
    }

    public static SqlSession get() {
        return factory.openSession();
    }
    //传入是否自动提交的参数
    public static SqlSession get(boolean autoCommit) {
        return factory.openSession(autoCommit);
    }
    public static void close(SqlSession s){
        if(s!=null)
        {
            s.commit();
            s.close();
        }
    }
}
